//
//  PlayManager.m
//  AVPlay
//
//  Created by darker on 16/3/23.
//  Copyright © 2016年 💋. All rights reserved.
//

#import "PlayManager.h"
#import "musicRunModel.h"
#import "AppDelegate.h"
#import "Entity+CoreDataProperties.h"
#import "Entity.h"
@interface PlayManager ()

@property (nonatomic, strong) AVPlayer *avPlayer;

@property(nonatomic,strong)NSManagedObjectContext * context;

@end


@implementation PlayManager

+(instancetype)sharedManager
{
    static PlayManager *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[PlayManager alloc] init];
    });
    return player;
}

- (instancetype)init
{
    if (self = [super init])
    {
        _avPlayer = [[AVPlayer alloc] init];
        _index = 0;
        
        
        
    }
    return self;
}

// 拿到外界传过来的数组只会就可以播放了, 所以可以重写set方法
-(void)setMusicArray:(NSArray *)musicArray
{
    
    AppDelegate * delegate = [UIApplication sharedApplication].delegate;
    
    _context = delegate.managedObjectContext;

    
    
    _musicArray = musicArray;
    
    NSURL *url =[NSURL URLWithString:_musicArray[_index]];
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[UIApplication sharedApplication]beginReceivingRemoteControlEvents];
    // 使用 AVPlayerItem可以获取歌曲的更多信息 (比如 总时间 当前时间)
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url];
    
    [_avPlayer replaceCurrentItemWithPlayerItem:item];
    
    [_avPlayer play];
    
    
    [self saveMOdel];
    

}
- (void)saveMOdel
{
    
    BOOL isHave = NO;
    
    NSFetchRequest * request = [[NSFetchRequest alloc]initWithEntityName:@"Entity"];
    
    NSPredicate * cate = [NSPredicate predicateWithFormat:@"isCollection= '0'"];
    
    [request setPredicate:cate];
    
    
    musicRunModel * model = _modelArray[_index];
  
    
    NSArray * array = [_context executeFetchRequest:request error:nil];
    
    NSMutableArray * arr = [NSMutableArray arrayWithArray:array];
    
    if (array.count == 0) {
        
        Entity  * c = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:_context];
        
        c.name = model.name;
        c.albumUrl = model.albumUrl;
        c.author = model.author;
        c.introduce = model.introduce;
        c.url = model.url;
        c.tableName = model.tableName;
        c.bpm = [NSNumber numberWithInteger:model.bpm];
        c.isCollection = [NSNumber numberWithBool:NO];
        [_context save:nil];
        
    }
    else
    {
        
        
        for (int i = 0; i < arr.count; i++) {
            if ([[arr[i] name] isEqualToString:model.name]) {
                 [_context deleteObject:arr[i]];
               Entity  * c = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:_context];
                c.name = model.name;
                c.albumUrl = model.albumUrl;
                c.author = model.author;
                c.introduce = model.introduce;
                c.url = model.url;
                c.bpm = [NSNumber numberWithInteger:model.bpm];
                c.isCollection = [NSNumber numberWithBool:NO];
                
                
                isHave = YES;
                [_context save:nil];
            }
            
        }
        
        
        
        if (!isHave) {
        
                Entity  * c = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:_context];
                
                c.name = model.name;
                c.albumUrl = model.albumUrl;
                c.author = model.author;
                c.introduce = model.introduce;
                c.url = model.url;
                c.bpm = [NSNumber numberWithInteger:model.bpm];
                c.isCollection = [NSNumber numberWithBool:NO];
                [_context save:nil];
            }

        }
    
    
        
        
        
    

}

// 为了方便我们点击tableView的时候 可以根据点击的单元格下标 直接跳转到对应的歌曲
- (void)changeMusicWithIndex:(NSInteger)index
{
    
    
    _index = index; // 外界更换歌曲之后 重新赋值
    
    NSURL *url =[NSURL URLWithString:_musicArray[index]];
    
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url];
    
    [_avPlayer replaceCurrentItemWithPlayerItem:item];
    
    [_avPlayer play];
    
    [self saveMOdel];
    
}

#pragma mark --- 上一首 ---
- (void)preMusic
{
   // NSInteger oldIndex = _index;
    _index -= 1;
    if (_index == - 1)
    {
        _index = _musicArray.count - 1;
    }
//    // 随机播放
//    if (_playtype == PlayTypeRandom)
//    {
//        if (_musicArray.count != 1)
//        {
//            do {
//                _index = arc4random() % _musicArray.count;
//                
//            } while (oldIndex == _index);
//        }
//    }
    [self changeMusicWithIndex:_index];
}

#pragma mark --- 下一首 ---
- (void)nextMusic
{
 //   NSInteger oldIndex = _index;
    _index += 1;
    
    if (_index == _musicArray.count)
    {
        _index = 0;
    }
//    // 随机播放
//    if (_playtype == PlayTypeRandom)
//    {
//        if (_musicArray.count != 1)
//        {
//            do {
//                _index = arc4random() % _musicArray.count;
//
//            } while (oldIndex == _index);
//        }
//    }
    [self changeMusicWithIndex:_index];
    
    
}

-(NSInteger)currentTime
{
    // 表示AVPlayer的时间都是CMTimt类型的结构体, 结构体中 value代表总帧数 timescale代表每秒多少帧
    
    if (_avPlayer.currentTime.timescale == 0)
    {
        return 0;
    }
    return _avPlayer.currentTime.value / _avPlayer.currentTime.timescale;
}

- (NSInteger)finishTime
{
    CMTime time = _avPlayer.currentItem.duration;
    
    if (time.timescale == 0)
    {
        return 0;
    }
    return time.value / time.timescale;
}

-(void)seekToTime:(NSInteger)newtime
{
    // 计算机识别歌曲进度的时候是按照帧数来计算的  帧数 = 每秒多少帧 * 秒数
    [_avPlayer seekToTime:CMTimeMake(newtime * _avPlayer.currentTime.timescale, _avPlayer.currentTime.timescale)];
}

#pragma mark --- 播放 ---
-(void)play
{
    
   
    
     [_avPlayer play];
}

#pragma mark --- 暂停 ---
-(void)pause
{
    [_avPlayer pause];
}

#pragma mark --- 歌曲播放完成之后的操作 ---
-(void)playDidFinish
{
    if (_playtype == PlayTypeRandom)
    {
        [self seekToTime:0];
    }
    else
    {
        [self nextMusic];
    }
    
}

#pragma mark --- 判断暂停还是播放 ---
-(BOOL)isPlaying
{
    // rate是播放的一个属性 0.0表示没在播放
    if (_avPlayer.rate == 0.0)
    {
        return NO;
    }
    return YES;
}

//- (NSString)currentTime
//{
//    return _avPlayer.currentTime.value;
//}



@end
